import React from 'react';
import { connect } from 'umi';
import { Modal, Radio, Space, Switch, InputNumber } from 'antd';
import { configModal } from '@/assets';
import { NumberSub } from '@/utils';
import { PowerStrategyType } from '@/pages/Tianji/DayRollingTradeStrategy/constant.js';

import styles from './index.less';

function PowerSettingModal({ hourOrderList, strategyPowerType, capacity, dispatch }, ref) {
  React.useImperativeHandle(ref, () => ({
    initHandle,
  }));

  const [showModal, setShowModal] = React.useState(false),
    [strategyType, setStrategyType] = React.useState(PowerStrategyType.POWER),
    [targetHoldings, setTargetHoldings] = React.useState(true),
    [powerRadio, setPowerRadio] = React.useState(0.8);

  const initHandle = () => {
    setShowModal(true);
  };

  const confirm = () => {
    // 设置策略计算电量展示口径
    dispatch({
      type: 'dayRollingTradeStragety/setStrategyPowerType',
      payload: strategyType,
    });
    // 计算24个时点的电量数据
    let hourOrderListNew = JSON.parse(JSON.stringify(hourOrderList));
    if (targetHoldings) {
      hourOrderListNew.forEach((item) => {
        let targetPosition = item.forecastForce * powerRadio;
        /**
         * 目标仓位
         * 最大值：装机容量 和 已有持仓量+卖出限额 两者中的较小值
         * 最小值：0 和 已有持仓量-买入限额 两者中的较大值
         *
         * 交易量=目标仓位-已有持仓量
         */
        let targetMax = Math.min(capacity, item.holdings + item.sellLimit);
        let targetMin = Math.max(0, item.holdings - item.buyLimit);
        if (targetPosition > targetMax) {
          targetPosition = targetMax;
        } else if (targetPosition < targetMin) {
          targetPosition = targetMin;
        }
        targetPosition = NumberSub(targetPosition, 3);

        let tradePower = NumberSub(targetPosition - item.holdings, 3);
        item.strategyPower =
          strategyType === PowerStrategyType.TARGET_POSITION ? targetPosition : tradePower;
        item.strategyPowerComputed = false;
        item.strategyPriceComputed = false;
        item.strategyBenefitsComputed = false;
      });
    } else {
      if (strategyType !== strategyPowerType) {
        hourOrderListNew.forEach((item) => {
          item.strategyPower =
            strategyType === PowerStrategyType.TARGET_POSITION
              ? NumberSub(item.strategyPower + item.holdings, 3)
              : NumberSub(item.strategyPower - item.holdings, 3);
        });
      }
    }
    dispatch({
      type: 'dayRollingTradeStragety/setHourOrderList',
      payload: hourOrderListNew,
    });

    setShowModal(false);
  };

  return (
    <Modal
      className={styles.powerSettingModal}
      centered={true}
      title={
        <div className={styles.modalTitle}>
          <img src={configModal} />
          <span className={styles.text}>策略电量设置</span>
        </div>
      }
      visible={showModal}
      okText="确认"
      onCancel={() => {
        setShowModal(false);
      }}
      onOk={confirm}
    >
      <div className={styles.powerStrategyType}>
        <span className={styles.label}>展示口径</span>
        <Radio.Group
          onChange={(e) => {
            setStrategyType(e.target.value);
          }}
          value={strategyType}
        >
          <Space direction="vertical">
            <Radio value={PowerStrategyType.TARGET_POSITION}>目标仓位 (已持仓+变动量)</Radio>
            <Radio value={PowerStrategyType.POWER}>交易量 (变动量)</Radio>
          </Space>
        </Radio.Group>
      </div>
      <div className={styles.targetPosition}>
        <span className={styles.label}>目标仓位</span>
        <div className={styles.item}>
          <Switch
            size="small"
            checked={targetHoldings}
            onChange={(checked) => {
              setTargetHoldings(checked);
            }}
          />
          <div className={styles.powerRadio}>
            <span className={styles.text}>出力预测</span>
            <span className={styles.text}>×</span>
            <InputNumber
              className={styles.input}
              precision={1}
              value={powerRadio * 100}
              onBlur={(e) => {
                let value = e.target.value;
                if (value === '' || !/^[-]?[\.\d]+$/.test(value)) return;
                let min = 0;
                if (value < min) {
                  value = min;
                }
                value = NumberSub(value, 1);
                setPowerRadio(value / 100);
              }}
            />
            <span>%</span>
          </div>
        </div>
      </div>
    </Modal>
  );
}

export default connect(
  ({ dayRollingTradeStragety }) => ({
    hourOrderList: dayRollingTradeStragety.hourOrderList,
    strategyPowerType: dayRollingTradeStragety.strategyPowerType,
    capacity: dayRollingTradeStragety.capacity,
  }),
  null,
  null,
  { forwardRef: true },
)(React.forwardRef(PowerSettingModal));
